/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Formulario_empregado.java
 *
 * Created on 11/06/2011, 14:18:08
 */

package formularios;

import formularios.model.Empregados;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.text.MaskFormatter;

/**
 *
 * @author Ramon
 */
public class Formulario_empregado extends javax.swing.JInternalFrame {

    /** Creates new form Formulario_empregado */
    public Formulario_empregado() {

        initComponents();
        //quando apertar enter, o botão salvar será acionado
        getRootPane().setDefaultButton(btn_emp_salvar);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        radGroup_emp_sexo = new javax.swing.ButtonGroup();
        lab_emp_cpf = new javax.swing.JLabel();
        lab_emp_nome = new javax.swing.JLabel();
        lab_emp_dtns = new javax.swing.JLabel();
        lab_emp_sexo = new javax.swing.JLabel();
        lab_emp_tel = new javax.swing.JLabel();
        lab_emp_end = new javax.swing.JLabel();
        lab_emp_email = new javax.swing.JLabel();
        lab_emp_cargo = new javax.swing.JLabel();
        lab_emp_hiredate = new javax.swing.JLabel();
        try {
            MaskFormatter formato_cpf = new MaskFormatter("###.###.###-##");
            txt_emp_cpf = new JFormattedTextField(formato_cpf);
            txt_emp_nome = new javax.swing.JTextField();
            MaskFormatter formato_dtns1 = new MaskFormatter("##/##/####");
            txt_emp_dtns = new JFormattedTextField(formato_dtns1);
            MaskFormatter formato_telefone = new MaskFormatter("(##)####-####");
            txt_emp_tel = new JFormattedTextField(formato_telefone);
            txt_emp_end = new javax.swing.JTextField();
            txt_emp_email = new javax.swing.JTextField();
            cbo_emp_cargo = new javax.swing.JComboBox();
            MaskFormatter formato_dtns2 = new MaskFormatter("##/##/####");
            txt_emp_hiredate = new JFormattedTextField(formato_dtns2);
            btn_emp_salvar = new javax.swing.JButton();
            btn_emp_limpar = new javax.swing.JButton();
            rad_emp_masc = new javax.swing.JRadioButton();
            rad_emp_fem = new javax.swing.JRadioButton();
            btn_emp_excluir = new javax.swing.JToggleButton();
            lab_emp_sal = new javax.swing.JLabel();
            txt_emp_sal = new MoedaTextField();

            setClosable(true);
            setIconifiable(true);
            setMaximizable(true);
            setResizable(true);
            setTitle("Formulário de Empregado");

            lab_emp_cpf.setText("CPF");

            lab_emp_nome.setText("Nome Completo");

            lab_emp_dtns.setText("Data de Nascimento");

            lab_emp_sexo.setText("Sexo");

            lab_emp_tel.setText("Telefone");

            lab_emp_end.setText("Endereço");

            lab_emp_email.setText("E-mail");

            lab_emp_cargo.setText("Cargo");

            lab_emp_hiredate.setText("Data de admissão");

        } catch (ParseException ex) {
            Logger.getLogger(Formulario_cliente.class.getName()).log(Level.SEVERE, null, ex);
        }
        txt_emp_cpf.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txt_emp_cpfFocusLost(evt);
            }
        });

        cbo_emp_cargo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        btn_emp_salvar.setText("Salvar");
        btn_emp_salvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_emp_salvarActionPerformed(evt);
            }
        });

        btn_emp_limpar.setText("Limpar");
        btn_emp_limpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_emp_limparActionPerformed(evt);
            }
        });

        radGroup_emp_sexo.add(rad_emp_masc);
        rad_emp_masc.setText("Masculino");

        radGroup_emp_sexo.add(rad_emp_fem);
        rad_emp_fem.setText("Feminino");

        btn_emp_excluir.setText("Excluir");
        btn_emp_excluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_emp_excluirActionPerformed(evt);
            }
        });

        lab_emp_sal.setText("Salário");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lab_emp_nome)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txt_emp_nome, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lab_emp_cpf)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txt_emp_cpf, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lab_emp_dtns)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txt_emp_dtns))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lab_emp_tel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txt_emp_tel, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lab_emp_sexo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(rad_emp_fem)
                            .addComponent(rad_emp_masc))))
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lab_emp_end)
                        .addGap(10, 10, 10)
                        .addComponent(txt_emp_end, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lab_emp_hiredate)
                        .addGap(6, 6, 6)
                        .addComponent(txt_emp_hiredate, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(lab_emp_cargo)
                                .addComponent(lab_emp_email))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(cbo_emp_cargo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                                    .addComponent(lab_emp_sal)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(txt_emp_sal, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(10, 10, 10))
                                .addComponent(txt_emp_email, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(btn_emp_salvar)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(btn_emp_excluir)
                            .addGap(18, 18, 18)
                            .addComponent(btn_emp_limpar))))
                .addGap(18, 18, 18))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_emp_cpf)
                            .addComponent(txt_emp_cpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_emp_nome)
                            .addComponent(txt_emp_nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_emp_dtns)
                            .addComponent(txt_emp_dtns, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_emp_tel)
                            .addComponent(txt_emp_tel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_emp_end)
                            .addComponent(txt_emp_end, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_emp_email)
                            .addComponent(txt_emp_email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_emp_cargo)
                            .addComponent(cbo_emp_cargo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lab_emp_sal)
                            .addComponent(txt_emp_sal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lab_emp_hiredate)
                            .addComponent(txt_emp_hiredate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btn_emp_salvar)
                            .addComponent(btn_emp_excluir)
                            .addComponent(btn_emp_limpar)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(rad_emp_masc)
                            .addComponent(lab_emp_sexo))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rad_emp_fem)))
                .addContainerGap(53, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_emp_salvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_emp_salvarActionPerformed

        char sexo = 0;
        String str_sal = "";

        //cria uma instancia relacionada ao contexto de persistencia
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("BancoImobiliaria");
        EntityManager em = emf.createEntityManager();
        //cria uma instancia para controlar a transação
        EntityTransaction trans = em.getTransaction();

        //vefirica qual sexo está selecionado
        if(rad_emp_masc.isSelected())
            sexo = 'M';
        else if(rad_emp_fem.isSelected())
            sexo = 'F';

        DateFormat formato_dtns = new SimpleDateFormat("dd/MM/yyyy");

        //verifica se a data é real
        formato_dtns.setLenient(false);

        //transforma a String dtns em Date
        Date dtns = null;

        try {
            dtns = formato_dtns.parse(txt_emp_dtns.getText());
        } catch (ParseException ex) {
            //Logger.getLogger(Formulario_cliente.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, "Data de nascimento inválida.");
            return;
        }

		//formato para data
        DateFormat formato_hiredate = new SimpleDateFormat("dd/MM/yyyy");

        //verifica se a data é real
        formato_hiredate.setLenient(false);
        
        Date hiredate = null;

        try {
            //transforma a String hiredate em Date
            hiredate = formato_hiredate.parse(txt_emp_hiredate.getText());
        } catch (ParseException ex) {
            //Logger.getLogger(Formulario_cliente.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, "Hiredate inválido.");
            return;
        }

        //muda a str_sal para ser possível transformá-la em double
        str_sal = txt_emp_sal.getText();
        str_sal = str_sal.replace(".", "");
        str_sal = str_sal.replaceAll(",", ".");

        //instancia da classe Empregados
        Empregados emp = new Empregados(txt_emp_cpf.getText(), txt_emp_nome.getText(),
                                        dtns, sexo, txt_emp_end.getText(), txt_emp_email.getText(),
                                        String.valueOf(cbo_emp_cargo.getSelectedItem()), 
                                        Double.parseDouble(str_sal), hiredate, txt_emp_tel.getText());

        try {
            //insere ou atualiza um empregado
            trans.begin();
            em.merge(emp);
            trans.commit();
            JOptionPane.showMessageDialog(this, "Empregado cadastrado com sucesso.");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Erro ao inserir. Por favor, confira os dados.");
        }

        //encerra a transação
        em.close();
        emf.close();
    }//GEN-LAST:event_btn_emp_salvarActionPerformed

    private void btn_emp_excluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_emp_excluirActionPerformed

        //verifica se existe algum cpf digitado
        if(txt_emp_cpf.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Entre com o CPF do empregado para excluí-lo.");
            txt_emp_cpf.requestFocus();
        }else
        {
            //cria gerenciador do BancoImobiliaria
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("BancoImobiliaria");
            EntityManager em = emf.createEntityManager();

            //procura o empregado com o CPF digitado
            Empregados emp = em.find(Empregados.class, txt_emp_cpf.getText());

            //verifica se o empregado existe
            if(emp == null) {
                JOptionPane.showMessageDialog(this, "CPF do empregado não encontrado. Entre com o CPF correto.");
                txt_emp_cpf.requestFocus();
            }else
            {
                //mensagem de alerda da exclusão do empregado
                if (JOptionPane.showConfirmDialog(this,
                        "Esta operação não poderá ser desfeita.\n Deseja continuar?",
                        "Aviso",
                        JOptionPane.YES_NO_OPTION,
                        JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION)
                    return;

                //obtem uma transação
                EntityTransaction trans = em.getTransaction();

                //remove empregado
                trans.begin();
                em.remove(emp);
                trans.commit();

                //encerra a transação
                em.close();
                emf.close();

                limparCampos();
            }
        }
    }//GEN-LAST:event_btn_emp_excluirActionPerformed

    private void btn_emp_limparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_emp_limparActionPerformed

        limparCampos();
    }//GEN-LAST:event_btn_emp_limparActionPerformed

    private void txt_emp_cpfFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txt_emp_cpfFocusLost

        //cria gerenciador do BancoImobiliaria
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("BancoImobiliaria");
        EntityManager em = emf.createEntityManager();

        //procura o empregado com o CPF digitado
        Empregados emp = em.find(Empregados.class, txt_emp_cpf.getText());

        //se o Objeto emp existir, mostra seus dados
        if(emp != null) {

            //formato para mostrar data
            SimpleDateFormat f_dtns = new SimpleDateFormat("dd/MM/yyyy");

            //transforma as datas dtns e hiredate no formato de data f_dtns
            String dtns = f_dtns.format(emp.getDtns());
            String hiredate = f_dtns.format(emp.getHiredate());

            txt_emp_nome.setText(emp.getNome());
            txt_emp_dtns.setText(dtns);
            txt_emp_tel.setText(emp.getTelefone());
            txt_emp_email.setText(emp.getEmail());
            txt_emp_end.setText(emp.getEndereco());
            txt_emp_hiredate.setText(hiredate);
            //cbo_emp_cargo.setSelectedIndex(emp.getCargo());

            //máscara para moeda em real
            Locale brasil = new Locale("pt","BR");
            DecimalFormatSymbols real = new DecimalFormatSymbols(brasil);
            DecimalFormat dinheiro_real = new DecimalFormat("###,###,##0.00",real);

            //mostra o salário com a máscara da moeda real
            txt_emp_sal.setText(dinheiro_real.format(emp.getSalario()));

            //seleciona o sexo do empregado
            if(emp.getSexo() == 'M')
                rad_emp_masc.setSelected(true);
            else if(emp.getSexo() == 'F')
                rad_emp_fem.setSelected(true);

            //encerra a trasação
            em.close();
            emf.close();
        }else {
            //limpa todos os campos exceto o CPF
            txt_emp_nome.setText("");
            txt_emp_dtns.setText("");
            txt_emp_tel.setText("");
            txt_emp_end.setText("");
            txt_emp_email.setText("");
            rad_emp_masc.setSelected(false);
            rad_emp_fem.setSelected(false);
            txt_emp_hiredate.setText("");
            cbo_emp_cargo.setSelectedIndex(1);
            txt_emp_sal.setText("");
        }
    }//GEN-LAST:event_txt_emp_cpfFocusLost

    void limparCampos()
    {
        //limpa todos os campos do Formulario_empregado
        txt_emp_cpf.setText("");
        txt_emp_nome.setText("");
        txt_emp_dtns.setText("");
        txt_emp_tel.setText("");
        txt_emp_end.setText("");
        txt_emp_email.setText("");
        rad_emp_masc.setSelected(false);
        rad_emp_fem.setSelected(false);
        txt_emp_hiredate.setText("");
        cbo_emp_cargo.setSelectedIndex(1);
        txt_emp_sal.setText("");

        //aponta cursor para o campo cpf
       // txt_emp_cpf.requestFocus();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToggleButton btn_emp_excluir;
    private javax.swing.JButton btn_emp_limpar;
    private javax.swing.JButton btn_emp_salvar;
    private javax.swing.JComboBox cbo_emp_cargo;
    private javax.swing.JLabel lab_emp_cargo;
    private javax.swing.JLabel lab_emp_cpf;
    private javax.swing.JLabel lab_emp_dtns;
    private javax.swing.JLabel lab_emp_email;
    private javax.swing.JLabel lab_emp_end;
    private javax.swing.JLabel lab_emp_hiredate;
    private javax.swing.JLabel lab_emp_nome;
    private javax.swing.JLabel lab_emp_sal;
    private javax.swing.JLabel lab_emp_sexo;
    private javax.swing.JLabel lab_emp_tel;
    private javax.swing.ButtonGroup radGroup_emp_sexo;
    private javax.swing.JRadioButton rad_emp_fem;
    private javax.swing.JRadioButton rad_emp_masc;
    private javax.swing.JTextField txt_emp_cpf;
    private javax.swing.JTextField txt_emp_dtns;
    private javax.swing.JTextField txt_emp_email;
    private javax.swing.JTextField txt_emp_end;
    private javax.swing.JTextField txt_emp_hiredate;
    private javax.swing.JTextField txt_emp_nome;
    private javax.swing.JTextField txt_emp_sal;
    private javax.swing.JTextField txt_emp_tel;
    // End of variables declaration//GEN-END:variables

}
